package com.um.login.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.cs.framework.common.util.CommonUtils;
import com.cs.framework.common.util.IOUtils;
import com.cs.framework.core.context.Application;
import com.cs.framework.core.util.CoreConstant;
import com.cs.framework.web.util.RequestUtils;
import com.cs.framework.web.util.WebConstant;
import com.um.info.dto.base.UmUserDto;

/**
 * 登录检查
 * 
 * @author hedongzhou
 *
 */
public class LoginCheckFilter implements Filter {

	/**
	 * 资源路径
	 */
	private String[] resources;

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		if (!doForward((HttpServletRequest) request, response)) {
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig config) throws ServletException {
		Application application = (Application) config.getServletContext().getAttribute(
				WebConstant.APPLICATION_CONTEXT_ATTR);
		String resourcePath = (String) application.getProperty(WebConstant.RESOURCES_PROPERTY);

		if (CommonUtils.isNotEmpty(resourcePath)) {
			resources = resourcePath.split(CoreConstant.CONF_SEPARATE);
		}
	}

	public void destroy() {
	}

	private boolean doForward(HttpServletRequest request, ServletResponse response) throws ServletException,
			IOException {
		if (!RequestUtils.isAjax(request)) {
			String resource = RequestUtils.getResource(request);

			if (CommonUtils.isNotEmpty(resources)) {
				if (IOUtils.match(resources, resource)) {
					return false;
				}
			}

			UmUserDto umUserDto = (UmUserDto) request.getSession().getAttribute(WebConstant.CURRENT_USER);

			if (umUserDto == null) {
				request.getRequestDispatcher("/um/login/loginPage").forward(request, response);
				return true;
			} else if (CommonUtils.isEmpty(resource) || CommonUtils.isEmpty(resource.replaceAll("/", ""))
					|| "/um/login/loginPage".equals(RequestUtils.noSuffix(resource))) {
				request.getRequestDispatcher("/um/login/homePage").forward(request, response);
				return true;
			}
		}

		return false;
	}

}
